<!-- 域名阻断 -->
<template>
  <div> <!--  class="dashboard-editor-container" -->
    <el-row style="background: #fff; padding: 16px 16px 0;">
      <div class="top topSubmitBtn">
        <el-button 
          v-for="item in functionalArea" 
          :key="item.name" 
          @click="showDialog(item.name)"
          icon="el-icon-circle-plus-outline" 
          type="primary">
          {{ item.name }}
        </el-button>
        <el-button type="warning" icon="el-icon-refresh" @click="getData()">刷新页面</el-button>
      </div>
      <div>
        <el-table border :data="tableData" style="width: 100%; margin: 15px 0">
          <el-table-column prop="date" label="序号" type="index" align="left" width="80px"></el-table-column>
          <el-table-column prop="TransTime" label="提交任务日期" width="200" align="left"></el-table-column>
          <el-table-column prop="ChatTitle" label="任务类型" width="180" align="left"></el-table-column>
          <el-table-column prop="Question" label="AI需求" align="left" show-overflow-tooltip>
            <template slot-scope="scope">
              <span m="4">
                <span m="t-0 b-2" v-show="scope.row.demand.product">产品描述: {{ scope.row.demand.product }}; </span>
                <span m="t-0 b-2" v-show="scope.row.demand.company">公司描述: {{ scope.row.demand.company}}; </span>
                <span m="t-0 b-2" v-show="scope.row.demand.keyword">关键词: {{ scope.row.demand.keyword}}; </span>
                <span m="t-0 b-2" v-show="scope.row.demand.paragraphs">写作段落: {{ scope.row.demand.paragraphs}}; </span>
                <span m="t-0 b-2" v-show="scope.row.demand.modal">写作字数: {{ scope.row.demand.modal}}; </span>
                <span m="t-0 b-2" v-show="scope.row.demand.language">目标语言: {{ scope.row.demand.language}}; </span>
              </span>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120px" align="left">
            <template slot-scope="scope">
              <div v-if="scope.row.Status === 0">
                等待AI生成中
              </div>
              <div v-else-if="scope.row.Status === 2">
                <i class="el-icon-loading"></i>
                AI生成中
              </div>
              <div v-else-if="scope.row.Status === 1">
                <el-button size="mini" type="primary" @click="handlecheck(scope.row)">查看</el-button>
                <!-- <el-button size="mini" type="danger" @click="handleDelete(scope.row.url)">删除</el-button> -->
              </div>
              <div v-else>
                AI生成失败
              </div>
            </template>
          </el-table-column>
        </el-table>
        <el-pagination 
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange" 
          :current-page=pageNum
          :page-size=pageSize
          background 
          layout="total, prev, pager, sizes, next, jumper"
          :total="total">
        </el-pagination>
      </div>
    </el-row>
    <productIntroduction :name="name" :loading="loading" :dialogVisible.sync="dialogVisible" @closeDialog="closeDialog" @submit="submit"></productIntroduction>
    <answerDialog :answerForm="answerForm" :answerDialog.sync="answerDialog" @closeanswer="closeanswer"></answerDialog>
  </div>
</template>

<script>
import Cookies from 'js-cookie'
import { connrequest } from "@/api/firstPage";
import { parseTime } from "@/utils/index.js";
import productIntroduction from './components/productIntroduction.vue'
import answerDialog from './components/answerDialog.vue'
import elDragDialog from '@/directive/el-drag-dialog' // base on element-ui
export default {
  directives: { elDragDialog },
  components:{
    productIntroduction,
    answerDialog
  },
  data() {
    return {
      pageNum: 1,
      pageSize: 10,
      total: 0,
      loading: false,
      name: '',
      omainName: '',
      dialogVisible: false,
      answerDialog: false,
      timer: null,
      flag: false,
      answerForm: {},
      tableData:[],
      functionalArea: [
        {name: '产品介绍'},
        // {name: '原创博客'},
        // {name: '文章写作'},
        // {name: '新闻采集改写'}
      ],
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get('DefaultPageLength') * 1
    this.getData()
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
  },
  beforeDestroy() {
    if(this.timer) { //如果定时器还在运行 或者直接关闭，不用判断
      clearInterval(this.timer); //关闭
    }
  },
  methods:{
    async getData() {
      this.tableData = []
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter:{
          // StartTime: "",
          // EndTime: "",
          Status: 2,
          Name: sessionStorage.getItem('roles'),
          Descp: "",
          TransDate: ""
        }
      }
      const res = await connrequest('GetChatGPTLog', data)
      res.Data = res.Data || []
      this.flag = false
      res.Data.map(item => {
        item.TransTime = parseTime(item.TransTime)
        if(item.Question !== '' && JSON.parse(item.Question).messages){
          item.Question = JSON.parse(item.Question).messages[1]?.content
          item.demand = this.extractContent(item.Question)
        }
        if(item.Status === 0 || item.Status === 2){
          this.flag = true
        }
      })
      if(this.flag === false){
        window.clearInterval(this.timer);
      }
      this.tableData = res.Data
      this.total = res.Paging.TotalCount
    },
    showDialog(name){
      if(name !== '产品介绍'){
        this.$message.info('该功能还在开发中')
        return
      }
      this.name = name
      this.dialogVisible = true
    },
    closeDialog(){
      this.dialogVisible = false
    },
    closeanswer(){
      this.answerDialog = false
    },
    async submit(form){
      if(!form.product){
        this.$message.info('产品描述为必填')
        return false
      }
      const product = form.product;
      const companyDescription = form.company ? `,Combining company description: {${form.company}}` : '';
      const keywords = form.keyword ? `,Combine keywords: {${form.keyword}}` : '';
      const paragraphs = form.paragraphs ? form.paragraphs : '3';
      const writingTone = form.modal ? form.modal : 'formal';
      const wordCount = form.wordCount ? form.wordCount : '500';
      const language = form.language ? form.language : 'English';
      const prompt = `Write a product introduction, combining with product description: {${product}}${companyDescription}${keywords},in ${paragraphs} paragraphs. Use the writing tone of ${writingTone} and output approximately${wordCount} words of written content in ${language}.`;
      this.apiMessage = [{role: 'system', content: 'you are a helpful assistant.'}]
      this.apiMessage.push({role:'user', content: prompt})
      const Question = {
        model: 'gpt-3.5-turbo-0613',
        messages: this.apiMessage,
      }
      const data = {
        Data:{
          Name: sessionStorage.getItem('roles'),
          ChatTitle:"产品介绍",
          Question: JSON.stringify(Question),
          Action: 2
        }
      }
      const res = await connrequest('WriteChatGPTLog', data)
      if(res.Status.StatusCode === 0){
        this.$message.success('操作成功')
        this.dialogVisible = false
        this.getData()
        // this.timer = window.setInterval(() => {
        //   this.getData();
        // }, 6000);
      }
    },
    handlecheck(row){
      // let Question = JSON.parse(row.Question).messages[1].content
      let Answer = JSON.parse(row.Answer).choices[0].message.content
      this.answerForm = {product: this.extractContent(row.Question), AIanswer: Answer}
      this.answerDialog = true
    },
    handleDelete(item){
      this.$confirm('此操作将永久删除该域名, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async () => {
        let data = {
          Data:{URL: item}
        }
        const res = await connrequest('DelForbiddenURL', data)
        if(res.Status.StatusCode === 0){
          this.$message({
            type: 'success',
            message: '删除成功!'
          });
          this.getData()
          this.dialogVisible = false
        }
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消删除'
        });          
      });
    },
    extractContent(paragraph) {
      const productRegex = /(?<=product description: {)[^{}]+(?=})/;
      const keywordRegex = /(?<=Combine keywords: {)[^{}]+(?=})/;
      const companyRegex = /(?<=Combining company description: {)[^{}]+(?=})/;
      const paragraphsRegex = /(?<=in )[0-9]+(?= paragraphs\.)/;
      const modalRegex = /(?<=approximately)[^ ]+(?= words of written content)/;
      const wordCountRegex = /\d+(?= words of)/;
      const languageRegex = /(?<=written content in )\w+/;
      const product = paragraph.match(productRegex) ? paragraph.match(productRegex)[0] : '';
      const keyword = paragraph.match(keywordRegex) ? paragraph.match(keywordRegex)[0] : '';
      const company = paragraph.match(companyRegex) ? paragraph.match(companyRegex)[0] : '';
      const paragraphs = paragraph.match(paragraphsRegex) ? parseInt(paragraph.match(paragraphsRegex)[0]) : '';
      const modal = paragraph.match(modalRegex) ? paragraph.match(modalRegex)[0] : '';
      const wordCount = paragraph.match(wordCountRegex) ? parseInt(paragraph.match(wordCountRegex)[0]) : '';
      const language = paragraph.match(languageRegex) ? paragraph.match(languageRegex)[0] : '';
      return {
        product,
        keyword,
        company,
        paragraphs,
        modal,
        wordCount,
        language,
      };
    },
    handleSizeChange(val){
      this.pageNum = 1
      this.pageSize = val
      this.getData()
    },
    handleCurrentChange( pageNum ){
      this.pageNum = pageNum
      this.getData()
    },
  }
};
</script>
<style scoped lang='scss'>
/* @import url(); 引入css类 */
.top {
  display: flex;
  align-items: center;
  justify-content: flex-start;
  p{
    font-size: 15px;
    color: #409eff;
    padding-left: 20px;
  }
}
</style>